package de.lulusoft.anothertorrent.core.servers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import de.lulusoft.anothertorrent.core.AnotherTorrentCore;

public class ServerManager implements Serializable {

	private static final long serialVersionUID = 6185253140373523795L;
	private static final String FILENAME = "ServerManager.serialized";
	
	private ArrayList<Server> servers = null;
	
	public ServerManager()
	{
		this.servers = new ArrayList<Server>();
	}
	
	// TODO: Make name the id of a server
	public void addServer(Server server)
	{
		this.servers.add(server);
	}
	
	public void removeServer(Server server)
	{
		this.servers.remove(server);
	}
	
	public ArrayList<Server> getServers()
	{
		return servers;
	}
	
	/**
	 * Looks for a Server with the name name.
	 * If none exists null is returned.
	 * @param name
	 * @return
	 */
	public Server getServerByName(String name)
	{
		for (Server s : servers)
		{
			if (s.getName().equals(name))
				return s;
		}
		return null;
	}
	
	/**
	 * Checks whether there is a server with the
	 * given name.
	 * @param name
	 * @return
	 */
	public boolean serverExists(String name)
	{
		for (Server s : servers)
		{
			if (s.getName().equals(name))
				return true;
		}
		return false;
	}
	
	/**
	 * Loads the ServerManager from disk
	 * @return
	 */
	public static ServerManager load()
	{
		String filename = AnotherTorrentCore.getDefault().getStateLocation()
		+ "/" + FILENAME;
		if (new File(filename).exists())
		{
			FileInputStream fIn = null;
			ObjectInputStream oIn = null;
	   
			try
			{
				fIn= new FileInputStream(filename);
				oIn = new ObjectInputStream(fIn);
				ServerManager mgr = (ServerManager) oIn.readObject();
				return mgr;
			}catch(IOException e)
			{
				e.printStackTrace(); 
			}catch(ClassNotFoundException e)
			{
				e.printStackTrace(); 
			}finally
			{
				try 
				{
					oIn.close();
					fIn.close();
				} catch (IOException e1) 
				{
					e1.printStackTrace();
				}
			}
		}
		return new ServerManager();
	}
	
	/**
	 * Saves the ServerManager to disk.
	 */
	public void save()
	{
		FileOutputStream fOut=null;
		ObjectOutputStream oOut=null;
   
		try
		{
			fOut= new FileOutputStream(AnotherTorrentCore.getDefault().getStateLocation()
					+ "/" + FILENAME);
			oOut = new ObjectOutputStream(fOut);
			oOut.writeObject(this);
			
		}catch(IOException e){
			e.printStackTrace(); 
		}finally
		{
			try 
			{
			    oOut.flush();
			    oOut.close();
			    fOut.close();
			} catch (IOException e1) 
			{
				e1.printStackTrace();
			}
		}
	}
	
}
